package cn.virens.common.boot.dubbo.error.simple;

import cn.virens.common.boot.dubbo.error.VirensExceptionHandler;
import cn.virens.common.util.exception.APIException;
import org.apache.dubbo.common.extension.Activate;
import org.springframework.util.ClassUtils;

@Activate
public class VirensExceptionWithValidationException implements VirensExceptionHandler {
    @Override
    public APIException exceptionHandling(Throwable throwable) throws APIException {
        if (ClassUtils.isPresent("jakarta.validation.ConstraintViolationException", null)) {
            if (throwable instanceof jakarta.validation.ConstraintViolationException exception) {
                StringBuilder builder = new StringBuilder();

                for (var v : exception.getConstraintViolations()) {
                    builder.append(",").append(v.getMessage());
                }

                return newAPIException(builder);
            }
        }

        if (ClassUtils.isPresent("javax.validation.ConstraintViolationException", null)) {
            if (throwable instanceof javax.validation.ConstraintViolationException exception) {
                StringBuilder builder = new StringBuilder();

                for (var v : exception.getConstraintViolations()) {
                    builder.append(",").append(v.getMessage());
                }

                return newAPIException(builder);
            }
        }

        return null;
    }

    private APIException newAPIException(StringBuilder builder) throws APIException {
        return new APIException("VALID", builder.deleteCharAt(0).toString());
    }
}
